//
//  LLSearchSuggestionVC.m
//  LLSearchView
//
//  Created by 王龙龙 on 2017/7/25.
//  Copyright © 2017年 王龙龙. All rights reserved.
//

#import "LLSearchSuggestionVC.h"
#import "SearchCanBaoCCell.h"
#import "SearchSellerCell.h"
#import "SearchPaiPinCCell.h"
#import "AppBaseGoodItem.h"
#import "SearchGoodCCell.h"
#import "SearchStoreCell.h"

@interface LLSearchSuggestionVC ()<UITableViewDelegate, UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UITableView *contentView;
@property (nonatomic, strong) UICollectionView *contentCollcetionView;
@property (nonatomic, strong) UILabel *resultsLabel;
@property (nonatomic, copy)   NSString *searchTest;
@property (nonatomic, strong) NSMutableArray * searchResultData;
@property (nonatomic,assign) NSInteger page;

@end

@implementation LLSearchSuggestionVC

- (UITableView *)contentView
{
    if (!_contentView) {
        self.contentView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, KScreenWidth, KScreenHeight-88) style:UITableViewStylePlain];
        _contentView.delegate = self;
        _contentView.dataSource = self;
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.tableFooterView = [UIView new];
        _contentView.separatorColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
        _contentView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return _contentView;
}
-(UICollectionView *)contentCollcetionView
{
    if (!_contentCollcetionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        fl.scrollDirection = UICollectionViewScrollDirectionVertical;
        _contentCollcetionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, KScreenWidth, KScreenHeight-88) collectionViewLayout:fl];
        _contentCollcetionView.backgroundColor = [UIColor whiteColor];
        _contentCollcetionView.dataSource = self;
        _contentCollcetionView.delegate = self;
        _contentCollcetionView.scrollEnabled = YES;
        _contentCollcetionView.alwaysBounceVertical = YES;
        _contentCollcetionView.backgroundColor = [UIColor clearColor];
       
        // 注册cell、sectionHeader、secionFooter
//        [_contentCollcetionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"baseCell"];
        [_contentCollcetionView registerNib:[UINib nibWithNibName:@"SearchCanBaoCCell" bundle:nil] forCellWithReuseIdentifier:@"searchCanBaoCCell"];
        [_contentCollcetionView registerNib:[UINib nibWithNibName:@"SearchPaiPinCCell" bundle:nil] forCellWithReuseIdentifier:@"searchPaiPinCCell"];
        [_contentCollcetionView registerNib:[UINib nibWithNibName:@"SearchGoodCCell" bundle:nil] forCellWithReuseIdentifier:@"searchGoodCCell"];
    }
    return _contentCollcetionView;
}
-(UILabel *)resultsLabel
{
    if (!_resultsLabel) {
        _resultsLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, mScreenWidth, 44)];
        _resultsLabel.text = @"名称包含 “喜字罐” 的卖家有3人";
        _resultsLabel.textColor = [UIColor AxcUI_colorWithHexCode:@"#B4B4B4"];
        _resultsLabel.font = mTitleFont(14);
//        _resultsLabel.backgroundColor = [UIColor redColor];
    }
    return _resultsLabel;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
    self.searchResultData = [[NSMutableArray alloc]init];
//    [self.view addSubview:self.resultsLabel];
    [self.view addSubview:self.contentCollcetionView];
    self.contentCollcetionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self searchTestChangeWithTest:self.searchTest andRefresh:YES];
    }];
    self.contentCollcetionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
       [self searchTestChangeWithTest:self.searchTest andRefresh:YES];
    }];
    self.contentView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self searchTestChangeWithTest:self.searchTest andRefresh:YES];
    }];
    self.contentView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self searchTestChangeWithTest:self.searchTest andRefresh:YES];
    }];
    [self.view addSubview:self.contentView];
}
-(void)setSearchType:(NSInteger)searchType
{
    _searchType = searchType;
    if (searchType == 1 || searchType == 3) {
        self.contentView.hidden = YES;
        self.contentCollcetionView.hidden = NO;
    }else if(searchType == 2){
        self.contentView.hidden = NO;
        self.contentCollcetionView.hidden = YES;
    }
}
- (void)searchTestChangeWithTest:(NSString *)test
{
    [self searchTestChangeWithTest:test andRefresh:NO];
}
-(void)loadData
{
    if ([self.contentView.mj_header isRefreshing]) {
        self.page = 1;
    }
    if ([self.contentView.mj_footer isRefreshing]) {
        self.page ++;
    }
    [self searchTestChangeWithTest:self.searchTest andRefresh:YES];
}
- (void)searchTestChangeWithTest:(NSString *)test andRefresh:(BOOL)refresh
{
    
    if (!refresh) {
        self.page = 1;
    }
    _searchTest = test;
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    NSString * pageStr = [NSString stringWithFormat:@"%ld",self.page];
    setDickeyobj(parameters,pageStr, @"page");
    setDickeyobj(parameters, @"12", @"limit");
    NSInteger postType;
    if (self.searchType == 1) {
        postType = app_searchGood;
        setDickeyobj(parameters, test, @"content");
    }else if (self.searchType == 2) {
        postType = app_searchStore;
        setDickeyobj(parameters, test, @"content");
    }else  {
        postType = app_mall_plantGoods;
        setDickeyobj(parameters, test, @"key");
    }
    
    [PPNetworkHelper POST:postType parameters:parameters success:^(id responseObject) {
        [self.contentCollcetionView.mj_header endRefreshing];
        [self.contentCollcetionView.mj_footer endRefreshing];
        [self.contentView.mj_header endRefreshing];
        [self.contentView.mj_footer endRefreshing];
        if (self.page == 1 && self.searchResultData.count > 0) {
            [self.searchResultData removeAllObjects];
        }
        if (YJPPSUCCESS(responseObject)) {
            if (self.searchType == 1 || self.searchType == 3) {//搜索商品
                for (NSDictionary * infoDic in responseObject[@"data"][@"list"]) {
                    AppBaseGoodItem * item = [[AppBaseGoodItem alloc]init];
                    [item setValuesForKeysWithDictionary:infoDic];
                    [self.searchResultData addObject:item];
                }
            }else{
                for (NSDictionary * infoDic in responseObject[@"data"][@"list"]) {
                  
                    [self.searchResultData addObject:infoDic];
                }
            }
            
            if ([responseObject[@"data"][@"list"] count]<12) {
                if (self.searchType == 1) {
                    [self.contentCollcetionView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.contentView.mj_footer endRefreshingWithNoMoreData];
                }
            }
        }else{
            [AxcUI_Toast AxcUI_showCenterWithText:responseObject[@"desc"]];
        }
        if (self.searchType == 1 || self.searchType == 3) {
            [self.contentCollcetionView reloadData];
        }
        if (self.searchType == 2) {
            [self.contentView reloadData];
        }
    } failure:^(NSError *error) {
        [self.contentCollcetionView.mj_header endRefreshing];
        [self.contentCollcetionView.mj_footer endRefreshing];
        [self.contentView.mj_header endRefreshing];
        [self.contentView.mj_footer endRefreshing];
    } showLoading:nil];
}
#pragma mark - UITableViewDataSource -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchResultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchStoreCell * sellerCell = [[NSBundle mainBundle]loadNibNamed:@"SearchStoreCell" owner:self options:nil].lastObject;
    NSDictionary * infoDic = self.searchResultData[indexPath.row];
    sellerCell.nameLabel.text = infoDic[@"storeName"];
    [sellerCell.logoImageView sd_setImageWithURL:infoDic[@"doorImage"] placeholderImage:mImageByName(@"nil")];
    if ([infoDic[@"storeType"] isEqualToString:@"1"]) {
        sellerCell.stateLabel.text = @"专营店铺";
    }else{
        sellerCell.stateLabel.text = @"商家店铺";
    }
    return sellerCell;
}
#pragma mark - UITableViewDelegate -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchBlock) {
        NSDictionary * infoDic = self.searchResultData[indexPath.row];
        self.searchBlock(infoDic[@"storeid"],self.searchType);
    }
}
#pragma mark - UICollctionViewDataSource -
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.searchResultData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SearchGoodCCell *baseCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchGoodCCell" forIndexPath:indexPath];
    AppBaseGoodItem * goodItem = self.searchResultData[indexPath.row];
    baseCell.goodItem = goodItem;
    return baseCell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
     return CGSizeMake((mScreenWidth-15)/2,(mScreenWidth-15)*0.5+75);
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 5, 0, 5);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchBlock) {
        if (self.searchType == 1 || self.searchType == 3) {
            AppBaseGoodItem * goodItem = self.searchResultData[indexPath.row];
             self.searchBlock(goodItem.gid,self.searchType);
        }
        if (self.searchType == 2) {
    
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
